package com.cloud.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author root
 * @description TODO
 * @date 2020/11/27 14:18
 */
@RestController
@RequestMapping("txt")
public class TxtController {
    @RequestMapping("txt")
    public void txt(HttpServletResponse response) throws IOException {
        File file = new File("E:\\download\\武道仙帝.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] by = new byte[1024 * 8];
        int i;
        response.setCharacterEncoding("utf-8");   //设置处理编码
        //设置接收的长度,单位字节
        response.setHeader("Content-Length", ""+file.length());
        ServletOutputStream outputStream = response.getOutputStream();
        //URLEncoder.encode("CentOS7_min.rar","utf-8")把指定的字符串 转换为指定编码的String并返回
        response.setHeader("Content-Disposition","attachment; filename="+ URLEncoder.encode(file.getName(),"utf-8"));
        while ((i = fileInputStream.read(by)) != -1) {
            outputStream.write(by,0,i);
        }
        outputStream.flush();
        outputStream.close();
        fileInputStream.close();
        System.out.println("程序结束!");
    }
}
